import os
import logging
from mkdocs import utils
from mkdocs.plugins import BasePlugin
from mkdocs.config import config_options
from mkdocs.contrib.search.search_index import SearchIndex
import json
import urllib


log = logging.getLogger(__name__)
base_path = os.path.dirname(os.path.abspath(__file__))


class LangOption(config_options.OptionallyRequired):
    """ Validate Language(s) provided in config are known languages. """

    def get_lunr_supported_lang(self, lang):
        for lang_part in lang.split("_"):
            lang_part = lang_part.lower()
            if os.path.isfile(os.path.join(base_path, 'lunr-language', f'lunr.{lang_part}.js')):
                return lang_part

    def run_validation(self, value):
        if isinstance(value, str):
            value = [value]
        elif not isinstance(value, (list, tuple)):
            raise config_options.ValidationError('Expected a list of language codes.')
        for lang in list(value):
            if lang != 'en':
                lang_detected = self.get_lunr_supported_lang(lang)
                if not lang_detected:
                    log.info(f"Option search.lang '{lang}' is not supported, falling back to 'en'")
                    value.remove(lang)
                    if 'en' not in value:
                        value.append('en')
                elif lang_detected != lang:
                    value.remove(lang)
                    value.append(lang_detected)
                    log.info(f"Option search.lang '{lang}' switched to '{lang_detected}'")
        return value


class SearchPlugin(BasePlugin):
    """ Add a search feature to MkDocs. """

    config_scheme = (
        ('lang', LangOption()),
        ('separator', config_options.Type(str, default=r'[\s\-]+')),
        ('min_search_length', config_options.Type(int, default=3)),
        ('prebuild_index', config_options.Choice((False, True, 'node', 'python'), default=False)),
        ('indexing', config_options.Choice(('full', 'sections', 'titles'), default='full'))
    )

    def on_config(self, config, **kwargs):
        "Add plugin templates and scripts to config."
        # print('===', self.search_index)
        self.config['cache_dir'] = config['cache_dir']
        if self.search_index:
            self.search_index.config['cache_dir']=self.config['cache_dir']
        if 'include_search_page' in config['theme'] and config['theme']['include_search_page']:
            config['theme'].static_templates.add('search.html')
        if not ('search_index_only' in config['theme'] and config['theme']['search_index_only']):
            path = os.path.join(base_path, 'templates')
            config['theme'].dirs.append(path)
            if 'search/main.js' not in config['extra_javascript']:
                config['extra_javascript'].append('search/main.js')
        if self.config['lang'] is None:
            # lang setting undefined. Set default based on theme locale
            validate = self.config_scheme[0][1].run_validation
            self.config['lang'] = validate(config['theme']['locale'].language)
        # The `python` method of `prebuild_index` is pending deprecation as of version 1.2.
        # TODO: Raise a deprecation warning in a future release (1.3?).
        if self.config['prebuild_index'] == 'python':
            log.info(
                "The 'python' method of the search plugin's 'prebuild_index' config option "
                "is pending deprecation and will not be supported in a future release."
            )
        return config

    def on_pre_dirty(self, config, **kwargs):
        # if self.search_index==None:
        self.search_index = SearchIndex(**self.config)
        self.search_index.clear_cache()
        pass

    def on_doing_dirty(self, context, **kwargs):
        # pass
        # log.info("==dirty==")
        # context['nav']= None
        # context['pages']=None
        # context['build_date_utc']=None
        # context['config']=None
        # context['page']=None
        # print(context)
        cache_name = 'index.json'
        cache_src = 'docs/'+context['page'].file.src_path
        cache_dir = "cache/"+context['page'].url
        cache_dest = cache_dir + cache_name
        # [x.key for x in context['config']['nav']]
        # print(context['page'].title)
        # print("file_src", cache_src)
        # if not os.path.exists(cache_dir):
        #     return
        # if not os.path.isfile(cache_dest):
        if not os.path.isfile(os.path.abspath(urllib.parse.unquote(cache_dest, encoding='utf-8', errors='replace'))):
            return
        # print(cache_src,cache_dest)
        self.search_index.add_cache(src_path=cache_src, cache_path=cache_dest)
        # with open(cache_dest, )
        # if not os.path.exists(cache_dest) or (os.path.isfile(os.path.abspath(cache_dest)) and os.path.getmtime(os.path.abspath(cache_dest)) < os.path.getmtime(os.path.abspath(cache_src))):
        #     print(1)
        # else:
        #     print(2)
        # if not os.path.exists(cache_dest):
        #     pass
        # else:
        #     pass
        pass

    def on_pre_build(self, config, **kwargs):
        "Create search index instance for later use."
        # self.search_index = SearchIndex(**self.config)

    def on_page_context(self, context, **kwargs):
        "Add page to search index."
        self.search_index.add_entry_from_context(context['page'])

    def on_post_build(self, config, **kwargs):
        "Build search index."
        output_base_path = os.path.join(config['site_dir'], 'search')
        search_index = self.search_index.generate_search_index()
        json_output_path = os.path.join(output_base_path, 'search_index.json')
        utils.write_file(search_index.encode('utf-8'), json_output_path)

        if not ('search_index_only' in config['theme'] and config['theme']['search_index_only']):
            # Include language support files in output. Copy them directly
            # so that only the needed files are included.
            files = []
            if len(self.config['lang']) > 1 or 'en' not in self.config['lang']:
                files.append('lunr.stemmer.support.js')
            if len(self.config['lang']) > 1:
                files.append('lunr.multi.js')
            if ('ja' in self.config['lang'] or 'jp' in self.config['lang']):
                files.append('tinyseg.js')
            for lang in self.config['lang']:
                if (lang != 'en'):
                    files.append(f'lunr.{lang}.js')

            for filename in files:
                from_path = os.path.join(base_path, 'lunr-language', filename)
                to_path = os.path.join(output_base_path, filename)
                utils.copy_file(from_path, to_path)
